package com.itheima.aspectaop;

import com.itheima.mapper.EmpLogMapper;
import com.itheima.project.log.EmpLog;
import com.itheima.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class TimeAspect {
    @Resource
    private EmpLogMapper empLogMapper;
    @Resource
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.project.costomannotation.log)")
    public Object recordRunTime(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        //获取用户id 获取操作人
        String url = request.getRequestURL().toString();
        if(url.contains("login")){
            Object[] args = pjp.getArgs();
            if(!(args==null)||!(args.length==0)){
                String loginInfo = Arrays.toString(args);
                empLogMapper.recordLogInfo(loginInfo,LocalDateTime.now());

            }
          return pjp.proceed();
        }
        String token = request.getHeader("token");
        Map<String, Object> empInfo = JwtUtil.ParseTwt(token);
        Integer operateEmpId = (Integer)empInfo.get("id");
        String operateName = (String) empInfo.get("name");
        //获取执行操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //获取类名
        String className = pjp.getTarget().getClass().getName();
        //获取方法名
        String methodName = pjp.getSignature().getName();
        //获取形参
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);
        //获取返回值
        Object result = pjp.proceed();
        String resultValue = result.toString();

        //获取耗时
        long end = System.currentTimeMillis();
        Long costTime = end-start;

        //封装
        EmpLog empLog = new EmpLog(null,operateTime,operateEmpId,className,methodName,methodParams,resultValue,operateName,costTime);
        empLogMapper.insert(empLog);
        //返回
        return result;
    }


}
